package cn.gov.pbc.dream.controller;

import cn.gov.pbc.dream.common.Const;
import cn.gov.pbc.dream.common.ResponseCode;
import cn.gov.pbc.dream.common.ServerResponse;
import cn.gov.pbc.dream.pojo.UserSession;
import cn.gov.pbc.dream.pojo.dto.user.LoginDto;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user/")
public class UserController {

    @PostMapping(value = "login.do")
    public ServerResponse login(HttpSession session, @RequestBody LoginDto loginDto) {
        UserSession userSession = new UserSession();
        if(loginDto != null){
            if(!loginDto.getUsername().equals("admin")){
                return ServerResponse.createByErrorMessage("用户名或者密码错误");
            }
            userSession.setId(0);
            userSession.setName("黄松祥");
            userSession.setDept("科技科");
            userSession.setRole(0);
            userSession.setRoleName("管理员");
            userSession.setOrg("人民银行温州市中心支行");
            session.setAttribute(Const.CURRENT_USER, userSession);
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByErrorMessage("用户名或者密码错误");
        }
//        return ServerResponse.createBySuccess(loginDto);
    }

    @PostMapping(value = "logout.do")
    public ServerResponse logout(HttpSession session) {
        session.invalidate();
        return ServerResponse.createBySuccess();
    }

    @PostMapping(value = "checkLogin.do")
    public ServerResponse checkLogin(HttpSession session) {
        UserSession userSession = (UserSession) session.getAttribute(Const.CURRENT_USER);
        if (userSession == null) {
            return ServerResponse.createByErrorCodeMessage(
                    ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        return ServerResponse.createBySuccess(userSession);
    }
}
